<template>
  <mars-dialog
    title="频谱"
    custom-class="zhyq-dialog detail-company-box"
    closeable
    v-bind="attrs"
    @resize="resize"
    width="600vw"
    :position="{ top: 50, bottom: 50, left: '25%' }"
  >
    <!-- Tab 导航 -->
    <div class="tab-nav">
      <button
        :class="{ active: activeTab === 'history' }"
        @click="switchTab('history')"
      >
        历史数据回顾
      </button>
      <button
        :class="{ active: activeTab === 'realtime' }"
        @click="switchTab('realtime')"
      >
        实时数据显示
      </button>
      <button
        :class="{ active: activeTab === 'ai' }"
        @click="switchTab('ai')"
      >
        AI 分析
      </button>
    </div>

    <!-- 可滚动容器 -->
    <div class="scrollable-wrapper">
      <div class="container">
        <div v-show="activeTab === 'realtime'" class="realtime-view" >
          <RealtimeSpectrum />
        </div>

        <div v-show="activeTab === 'history'" class="history-view" >
          <!-- 👇 所有图表交给 pd.vue 渲染 -->
          <RadioBandChart
            v-if="chartDataReady"
            :frequencies="frequencies"
            :freq-labels="freqLabels"
            :db-values="dbValues"
            :waterfall-data="waterfallData"
            :waterfall-times="waterfallTimes"
          />
        </div>
        <div v-show="activeTab === 'ai'" class="ai-view">
          <AIAnalysis />
        </div>
      </div>
    </div>
  </mars-dialog>
</template>

<script setup>
import { ref, onMounted } from "vue"
import RealtimeSpectrum from "./realtimeSpectrum.vue"
import RadioBandChart from "./pd.vue"
import AIAnalysis from "./AIAnalysis.vue"
// ========== refs & state ==========
const activeTab = ref("history")
const chartDataReady = ref(false)

// ========== 数据 ==========
const frequencies = ref([])
const freqLabels = ref([])
const dbValues = ref([])
const waterfallData = ref([])
const waterfallTimes = ref([])

// ========== CSV 配置 ==========
const CSV_URL =
  "http://file.hbkj-shs.com:9010/stations/ycTest/RFExplorer_MultipleSweepData_2025_09_04_16_43_02.csv"

// ========== Tab 切换 ==========
function switchTab(tab) {
  activeTab.value = tab
}

// ========== 解析 CSV ==========
async function loadAndParseCsv() {
  try {
    const response = await fetch(CSV_URL)
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`)
    }

    const text = await response.text()
    const lines = text.trim().split("\n").map(line => line.trim())

    if (lines.length < 6) {
      throw new Error("CSV 数据不足")
    }

    // 解析频率头（第6行）
    const headers = lines[5].split(",").map(h => h.trim())
    const freqs = headers.slice(4).map(f => parseFloat(f))
    frequencies.value = freqs
    freqLabels.value = freqs.map(f => f.toFixed(2))

    // 初始化
    const wData = []
    const wTimes = []
    let lastDbValues = []

    for (let i = 6; i < lines.length; i++) {
      const values = lines[i].split(",").map(v => v.trim())
      const date = values[1]
      const time = values[2]
      const scanTime = `${date} ${time}`
      const signalValues = values.slice(4).map(v => parseFloat(v))

      // 瀑布图数据 [xIndex, yIndex, dBm]
      signalValues.forEach((val, idx) => {
        wData.push([idx, i - 6, val])
      })

      wTimes.push(scanTime)
      if (i === lines.length - 1) {
        lastDbValues = [...signalValues]
      }
    }

    dbValues.value = lastDbValues
    waterfallData.value = wData
    waterfallTimes.value = wTimes
    chartDataReady.value = true

    console.log("✅ CSV 加载完成", { scans: wTimes.length })
  } catch (err) {
    console.error("❌ CSV 加载失败:", err)
  }
}

// ========== 挂载 ==========
onMounted(() => {
  loadAndParseCsv()
})
</script>

<style lang="less">
.detail-company-box {
  width: 50vw;
  height: 80vh;
  min-width: 930px;
  min-height: 750px;

  .pannel-model__header {
    background: none;
    height: 32px;
  }
}
</style>

<style lang="less" scoped>
.scrollable-wrapper {
  height: 100%;
  overflow-y: auto;
  padding: 0 12px 12px;
}

.container {
  min-height: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding-bottom: 16px;
}

.tab-nav {
  display: flex;
  gap: 2px;
  padding: 0 16px 12px;
  background: rgba(0, 0, 0, 0.2);
  border-bottom: 1px solid #444;

  button {
    padding: 8px 24px;
    background: transparent;
    border: 1px solid transparent;
    color: #aaa;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.2s;

    &:hover {
      color: #fff;
    }

    &.active {
      color: #fff;
      border-color: #00bcd4;
      background: rgba(0, 188, 212, 0.1);
    }
  }
}
</style>
